package com.googlecode.dgwt.client.dojox.data.model.base;

import com.googlecode.dgwt.client.dojo.data.format.ValueFormatter;
import com.googlecode.dgwt.client.dojo.exception.ValidationException;

/**
 * @author wellsantos@wellsantos.com
 * @since 0.01
 */
public abstract class DataColumnBase<Item, Type> extends NamedTableColumnBase<Item, Type> implements GridColumn<Item, Type> {

    private int maxLength = 0;
    
    public DataColumnBase() {
        super();
    }

    public DataColumnBase(String title) {
        super(title);
    }

    public DataColumnBase(int maxLength) {
        super();
        setMaxLength(maxLength);
    }

    public DataColumnBase(ValueFormatter<? extends Type> formatter) {
        super();
        setFormatter(formatter);
    }

    public DataColumnBase(String title, int maxLength) {
        super(title);
        setMaxLength(maxLength);
    }

    public DataColumnBase(String title, String width) {
        super(title);
        setWidth(width);
    }

    public DataColumnBase(String title, ValueFormatter<? extends Type> formatter) {
        super(title);
        setFormatter(formatter);
    }

    public DataColumnBase(String title, int maxLength, ValueFormatter<? extends Type> formatter) {
        super(title);
        setMaxLength(maxLength);
        setFormatter(formatter);
    }

    
    @Override
    public int getMaxLength() {
        return maxLength;
    }

    public void setMaxLength(int maxLength) {
        if (maxLength < 0) {
            maxLength = 0;
        }
        if (this.maxLength != maxLength) {
            this.maxLength = maxLength;
            onColumnChanged();
        }
    }

    @Override
    public void setDisplayValue(Item item, String value) throws ValidationException {
        if (getMaxLength() > 0 && value != null) {
            value = value.trim().substring(0, Math.min(getMaxLength(), value.length()));
        }        
        super.setDisplayValue(item, value);
    }

    @Override
    public String getDisplayValue(Item item) {
        String value = super.getDisplayValue(item);
        
        if (getMaxLength() > 0 && value != null) {
            value = value.trim().substring(0, Math.min(getMaxLength(), value.length()));
        }
        
        return value;
    }

}
